package com.yuyou.tas.report.controller;

import com.yuyou.tas.report.out.api.CustomerBindStudentVo;
import com.yuyou.tas.report.out.api.MUAPI;
import com.yuyou.tas.report.service.IExamModelReportService;
import com.yuyou.tas.report.service.IExamModelWordPassService;
import com.yuyou.tas.report.service.IStudentReportService;
import com.yuyou.tas.service.api.lesson.entity.BaseTrimester;
import com.yuyou.tas.service.api.lesson.entity.Student;
import com.yuyou.tas.service.api.lesson.req.ReqFilterOrganStuOIds;
import com.yuyou.tas.service.api.lesson.service.BaseDataAPI;
import com.yuyou.tas.service.api.lesson.service.StudentAPI;
import com.yuyou.tas.service.api.report.dto.*;
import com.yuyou.tas.service.api.report.entity.ExamModelReport;
import com.yuyou.tas.service.api.report.entity.ExamModelWordPass;
import com.yuyou.tas.util.bean.PageParams;
import com.yuyou.tas.util.bean.Pagination;
import com.yuyou.tas.util.bean.ReturnResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(value="StudentReportController",description="学生端学生报表接口")
@Validated
@RestController
@RequestMapping(value = "/terminal/api/student/")
public class TerminalStudentReportController extends BaseController{

	@Autowired
	private StudentAPI studentAPI;

	@Autowired
	private BaseDataAPI baseDataAPI;
	
	@Autowired
	private IStudentReportService studentReportService;

	@Autowired
	private IExamModelReportService examModelReportService;

	@Autowired
	private IExamModelWordPassService examModelWordPassService;
	
	/*@Autowired
	private IExamModelReportScoreConfigService scoreConfigService;*/
	
	@Autowired
	private MUAPI mUAPI;
	
	@ApiOperation(value = "查询所在机构的学期")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sysCode", value = "机构编号", paramType = "query", required = true)})
	@RequestMapping(value = "/findTrim", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ReturnResult<List<BaseTrimester>> findTrim(
			HttpServletRequest request,
			@NotNull(message = "机构编号不能为空") String sysCode) throws Exception {
		Long authOrganizationId=this.getOrganId(sysCode);
		List<BaseTrimester> list = baseDataAPI.findTrimByOran(authOrganizationId);
		return ReturnResult.success(list);
	}

	
	@ApiOperation(value = "查询绑定学生列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "accessToken", value = "accessToken", paramType = "query", required = true),
			@ApiImplicitParam(name = "sysCode", value = "机构编号", paramType = "query", required = true) })
	@RequestMapping(value = "/findCustomerBindStudent", method = {
			RequestMethod.GET, RequestMethod.POST })
	public ReturnResult<Student> findCustomerBindStudent(
			@NotBlank(message = "accessToken不能为空") String accessToken,
			@NotBlank(message = "sysCode不能为空") String sysCode) throws Exception {

		CustomerBindStudentVo vo = mUAPI.findCustomerBindStudent(accessToken);
		if (!vo.isSuccess() && vo.getDesc().indexOf("accessToken") != -1) {
			return ReturnResult.fail3001();
		}
		if (!vo.isSuccess()) {
			return ReturnResult.returnRes(vo.isSuccess(), vo.getDesc(), null);
		}
		// 过滤机构
		List<Long> oIds = vo.getData().stream()
				.map(item -> item.getStudentId()).collect(Collectors.toList());

		Long authOrganizationId = this.getOrganId(sysCode);
		List<Student> s = studentAPI
				.filterOrganByOIds(new ReqFilterOrganStuOIds(oIds,
						authOrganizationId));
		return ReturnResult.success(s);
	}
	
	

	@ApiOperation(value = "学生报告列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageIndex", value = "pageSize", paramType = "query", required = true),
			@ApiImplicitParam(name = "pageSize", value = "pageSize", paramType = "query", required = true),
			@ApiImplicitParam(name = "studentId", value = "学生ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "baseTrimesterId", value = "学期ID", paramType = "query", required = false),
			@ApiImplicitParam(name = "sysCode", value = "机构编号", paramType = "query", required = true)})
	@RequestMapping(value = "/reportStudentList", method = { RequestMethod.GET,RequestMethod.POST })
	public ReturnResult<List<ReportStudentDTO>> reportStudentList(HttpServletRequest request,
																  @Validated @ModelAttribute PageParams pageParams,
																  @NotNull(message = "学生ID不能为空") Long studentId,
																  @NotNull(message = "机构编号不能为空") String sysCode,
																  String baseTrimesterId) throws Exception {
		Long authOrganizationId=this.getOrganId(sysCode);
		Student student = studentAPI.selectByOrgan7OId(studentId,authOrganizationId);

		if(student==null){
			return ReturnResult.fail("没找到该学生信息");
		}

		Map<String, Object> conditions = new HashMap<>();
		Pagination<ReportStudentDTO> queryPgn = new Pagination<>();
		conditions.put("studentId", student.getId());
		conditions.put("authOrganizationId", student.getAuthOrganizationId());
		conditions.put("baseTrimesterId", baseTrimesterId);
		conditions.put("terminal", true);
		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);

		int total = studentReportService.findReportStudentCount(queryPgn);
		queryPgn.setTotal(total);
		queryPgn.toBePage();
		if(total > 0){
			List<ReportStudentDTO> list = studentReportService.findReportStudentPageList(queryPgn);
			queryPgn.setList(list);
		}
		return ReturnResult.success(queryPgn);
	}

	@ApiOperation(value = "根据手机号查询学生报告列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageIndex", value = "pageSize", paramType = "query", required = true),
			@ApiImplicitParam(name = "pageSize", value = "pageSize", paramType = "query", required = true),
			@ApiImplicitParam(name = "phoneNo", value = "手机号", paramType = "query", required = true),
			@ApiImplicitParam(name = "name", value = "姓名", paramType = "query", required = true)})
	@RequestMapping(value = "/reportListOfStudent", method = { RequestMethod.GET,RequestMethod.POST })
	public ReturnResult<List<ReportStudentDTO>> reportListOfStudent(HttpServletRequest request,
																	@Validated @ModelAttribute PageParams pageParams,
																	@NotNull(message = "手机号不能为空") String phoneNo,
																	@NotNull(message = "姓名") String name
																	) throws Exception {

		Map<String, Object> conditions = new HashMap<>();
		Pagination<ReportStudentDTO> queryPgn = new Pagination<>();
		conditions.put("phoneNo", phoneNo);
		conditions.put("name", name);
		conditions.put("terminal", true);
		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);

		int total = studentReportService.findReportStudentCount(queryPgn);
		if(total == 0){
			return ReturnResult.fail("查无该生，请先检查是否输入错误");
		}
		queryPgn.setTotal(total);
		queryPgn.toBePage();
		if(total > 0){
			List<ReportStudentDTO> list = studentReportService.findReportStudentPageList(queryPgn);
			queryPgn.setList(list);
		}
		return ReturnResult.success(queryPgn);
	}
	
	@ApiOperation(value = "01总体概况")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "reportId", value = "报告ID", paramType = "query", required = true),
		@ApiImplicitParam(name = "sysCode", value = "机构编号", paramType = "query", required = true)})
	@RequestMapping(value = "/reportInfo", method = { RequestMethod.GET,RequestMethod.POST })
	public ReturnResult<ReportStudentDTO> reportInfo(HttpServletRequest request,
			@NotNull(message = "报告ID") Long reportId,
			@NotNull(message = "机构编号不能为空") String sysCode
			){
		boolean checkReportUse=examModelReportService.checkReportUse(reportId);
		if(!checkReportUse){
			return ReturnResult.success();
		}
		ReportStudentDTO res=studentReportService.reportInfo(reportId,false);		
		return ReturnResult.success(res);
	}

	@ApiOperation(value = "02成绩整体情况")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "reportId", value = "报告ID", paramType = "query", required = true),
		@ApiImplicitParam(name = "sysCode", value = "机构编号", paramType = "query", required = true)})
	@RequestMapping(value = "/reportScore", method = { RequestMethod.GET,RequestMethod.POST })
	public ReturnResult<ReportScoreDTO> reportScore(HttpServletRequest request,
			@NotNull(message = "报告ID") Long reportId,
			@NotNull(message = "机构编号不能为空") String sysCode
			){
		boolean checkReportUse=examModelReportService.checkReportUse(reportId);
		if(!checkReportUse){
			return ReturnResult.success();
		}
		ReportScoreDTO res=studentReportService.reportScore(reportId);
		return ReturnResult.success(res);
	}

	@ApiOperation(value = "03难易度情况")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "reportId", value = "报告ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "sysCode", value = "机构编号", paramType = "query", required = true)})
	@RequestMapping(value = "/reportHard", method = { RequestMethod.GET,RequestMethod.POST })
	public ReturnResult<ReportHardDTO> reportHard(HttpServletRequest request,
												  @NotNull(message = "报告ID") Long reportId,
												  @NotNull(message = "机构编号不能为空") String sysCode){
		boolean checkReportUse=examModelReportService.checkReportUse(reportId);
		if(!checkReportUse){
			return ReturnResult.success();
		}
		List<ReportHardDTO> res=studentReportService.reportHard(reportId);
		return ReturnResult.success(res);
	}

	@ApiOperation(value = "04各试题得分情况")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "reportId", value = "报告ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "sysCode", value = "机构编号", paramType = "query", required = true)})
	@RequestMapping(value = "/reportQues", method = { RequestMethod.GET,RequestMethod.POST })
	public ReturnResult<ReportQuesDTO> reportQues(HttpServletRequest request,
												  @NotNull(message = "报告ID") Long reportId,
												  @NotNull(message = "机构编号不能为空") String sysCode){
		boolean checkReportUse=examModelReportService.checkReportUse(reportId);
		if(!checkReportUse){
			return ReturnResult.success();
		}
		ReportQuesDTO res=studentReportService.reportQues(reportId);
		return ReturnResult.success(res);
	}

	@ApiOperation(value = "05知识得分情况分析")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "reportId", value = "报告ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "sysCode", value = "机构编号", paramType = "query", required = true)})
	@RequestMapping(value = "/reportKnow", method = { RequestMethod.GET,RequestMethod.POST })
	public ReturnResult<ReportKnow> reportKnow(@NotNull(message = "报告ID不能为空") Long reportId){
		boolean checkReportUse=examModelReportService.checkReportUse(reportId);
		if(!checkReportUse){
			return ReturnResult.success();
		}
		ExamModelReport examModelReport = examModelReportService.selectByPrimaryKey(reportId);
//		Long authOrganizationId=this.getOrganId(sysCode);
//		Student student = studentAPI.selectByOrgan7OId(authOrganizationId, examModelReport.getStudentId());
		ReportKnow reportKnow = studentReportService.reportKnow(examModelReport.getStudentId(), examModelReport.getExamModelId(), examModelReport.getLessonClassId() ,examModelReport);
		return ReturnResult.success(reportKnow);
	}


	@ApiOperation(value = "05知识得分情况分析(文综)")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "reportId", value = "报告ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "sysCode", value = "机构编号", paramType = "query", required = true)})
	@RequestMapping(value = "/reportKnowI", method = { RequestMethod.GET,RequestMethod.POST })
	public ReturnResult<ReportKnowI> reportKnowI(@NotNull(message = "报告ID不能为空") Long reportId){
		boolean checkReportUse = examModelReportService.checkReportUse(reportId);
		if(!checkReportUse){
			return ReturnResult.success();
		}
		ExamModelReport examModelReport = examModelReportService.selectByPrimaryKey(reportId);
		ReportKnowI reportKnowI = studentReportService.reportKnowI(examModelReport.getStudentId(), examModelReport.getExamModelId(), examModelReport.getLessonClassId() ,examModelReport);
		return ReturnResult.success(reportKnowI);
	}


	@ApiOperation(value = "06报告达标情况")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "reportId", value = "报告ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "sysCode", value = "机构编号", paramType = "query", required = true)})
	@RequestMapping(value = "/reportPass", method = { RequestMethod.GET,RequestMethod.POST })
	public ReturnResult<ReportPassDTO> reportPass(@NotNull(message = "报告ID不能为空") Long reportId){
		boolean checkReportUse=examModelReportService.checkReportUse(reportId);
		if(!checkReportUse){
			return ReturnResult.success();
		}

		//查询总体信息
		ReportStudentDTO res=studentReportService.reportInfo(reportId,false);
		if(res == null){
			return ReturnResult.success();
		}

		//获取学生信息
		Student s = studentAPI.selectByPrimaryKey(res.getStudentId());
		if(s == null){
			return ReturnResult.success();
		}

		ReportPassDTO reportPassDTO = new ReportPassDTO();
		BeanUtils.copyProperties(res , reportPassDTO);
		reportPassDTO.setPhone(s.getPhoneNo());

		ExamModelWordPass examModelWordPass = examModelWordPassService.getByScore(res.getExamModelId() , reportPassDTO.getGetScore());
		if(examModelWordPass != null){
			reportPassDTO.setRemark(examModelWordPass.getPassRemark());
			reportPassDTO.setPassStr(examModelWordPass.getPassDescribe());
		}

		/*ExamModelReportScoreConfig scoreConfig=scoreConfigService.selectByBsId(s.getAuthOrganizationId(), res.getBaseSectionId());
		if(scoreConfig!=null){
			if(res.getGetScore().compareTo(new BigDecimal(scoreConfig.getPassScore())) >= 0){//达标
				reportPassDTO.setPassStr(scoreConfig.getPassDescribe());
				reportPassDTO.setRemark(scoreConfig.getPassRemark());
				reportPassDTO.setPassStatus(ExamModelEnums.passStatus.pass.getValue());
			}else{
				reportPassDTO.setPassStr(ReportConst.FAIL_DESCRIBE);
				reportPassDTO.setRemark(ReportConst.FAIL_REMAEK);
				reportPassDTO.setPassStatus(ExamModelEnums.passStatus.fail.getValue());
			}
		}
		else{
			if(res.getGetScore().compareTo(ReportConst.PASS_SCORE) >= 0){//达标
				reportPassDTO.setPassStr(ReportConst.PASS_DESCRIBE);
				reportPassDTO.setRemark(ReportConst.PASS_REMAEK);
				reportPassDTO.setPassStatus(ExamModelEnums.passStatus.pass.getValue());
			}else{
				reportPassDTO.setPassStr(ReportConst.FAIL_DESCRIBE);
				reportPassDTO.setRemark(ReportConst.FAIL_REMAEK);
				reportPassDTO.setPassStatus(ExamModelEnums.passStatus.fail.getValue());
			}
		}*/

		return ReturnResult.success(reportPassDTO);
	}

}
